package com.android.fragmentdemo.service
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.util.concurrent.TimeUnit

class WebSocketService : WebSocket {

    private lateinit var mOkHttpClient: OkHttpClient

    fun init() {
        mOkHttpClient =
            OkHttpClient
                .Builder()
                .pingInterval(10, TimeUnit.SECONDS)//ping间隔时间
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)//失败重连
                .build()

        val request =
            Request
                .Builder()
                .url(URL)
                //加token鉴权
                .addHeader("token", "this is a token")
                .build()

        mOkHttpClient.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                super.onOpen(webSocket, response)
                //webSocket已经打开
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                super.onMessage(webSocket, text)
                //接受消息
            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
                super.onMessage(webSocket, bytes)
                //接受消息
            }

            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosing(webSocket, code, reason)
                //正在关闭
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosed(webSocket, code, reason)
                //已经关闭
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                super.onFailure(webSocket, t, response)
                //连接失败
            }
        })
    }

    override fun request(): Request {
        return Request.Builder().build()
    }

    override fun queueSize(): Long {
        return Long.MAX_VALUE
    }

    override fun send(text: String): Boolean {
        return true
    }

    override fun send(bytes: ByteString): Boolean {
        return true
    }

    override fun close(code: Int, reason: String?): Boolean {
        return true
    }

    override fun cancel() {

    }

    companion object {
        const val URL = "https://www.baidu.com/"
    }
}